import { loginApi, getInfoApi, getDetailUserInfoApi } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    // 设置token
    setToken(state, data) {
      // 存入state
      state.token = data
      setToken(data)
    },
    // 清除token
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, data) {
      state.userInfo = data
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async loginAction(context, data) {
      // 发请求
      console.log(data) // data就是表格数据
      const res = await loginApi(data)
      console.log(res) // token
      // 触发mutations
      context.commit('setToken', res)
    },
    async getUserInfoAction(context) {
      // 发请求
      const res = await getInfoApi()
      console.log(res) // 用户信息
      // 触发mutations
      context.commit('setUserInfo', res)
      // 发请求
      const res2 = await getDetailUserInfoApi(res.userId)
      console.log(res2) // 用户详细信息
      // 触发mutations
      context.commit('setUserInfo', { ...res, ...res2 })
      // *返回用户信息
      return res
    },
    async quitAction(context) {
      // 清除token
      context.commit('removeToken')
      // 清除用户资料
      context.commit('removeUserInfo')
      // !重置路由实例
      resetRouter()
      // !重置侧边栏菜单(vuex里面user.js和permission.js两个模块，兄弟模块怎么调用mutation方法)
      //  context.commit('模块/方法',[],{root:true})
      context.commit('permission/setRoutes', [], { root: true })
    }
  }
}
